//
//  JTTYPGRViewController.m
//  Estate
//
//  Created by houzhen on 2017/11/4.
//  Copyright © 2017年 ttsx. All rights reserved.
//

#import "Tweet.h"
#import "PictureViewController.h"


#import "DefaineCell.h"
// 多行输入cell
#import "B_wuLiaoCell.h"
//附件选择框
#import "H1_ImagesCell.h"

#import "JJTYPZRViewController.h"

@interface JJTYPZRViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate,UITextViewDelegate>

@property (nonatomic,strong) UIImageView *imageEidtView ;
@property (nonatomic,strong) UITextView *bottomView;
@property (nonatomic,strong) UIButton *bottomButton;

/**表格*/
@property (strong ,nonatomic)TPKeyboardAvoidingTableView *tableView;
@property(strong,nonatomic)UIImagePickerController *picker;
//附件模型
@property (strong, nonatomic) Tweet *curTweet;
/**质检员数组*/
@property (nonatomic,strong) NSMutableArray *iqcArray;
/**安全员数组*/
@property (nonatomic,strong) NSMutableArray *safeArray;
/**测试员数组*/
@property (nonatomic,strong) NSMutableArray *testArray;

/**人员类型数据*/
@property (nonatomic,strong) NSArray *peopleTypeArr;




@end

@implementation JJTYPZRViewController
{
    NSMutableArray * _titleArr;
}

// 人员类型数据
- (NSArray *)peopleTypeArr {
    if (!_peopleTypeArr) {
        _peopleTypeArr = @[@"CONSTRACT_04", @"CONSTRACT_05", @"CONSTRACT_06"];
    }
    return _peopleTypeArr;
}

- (NSMutableArray *)iqcArray {
    if (!_iqcArray) {
        _iqcArray = [NSMutableArray array];
    }
    return _iqcArray;
}

-(NSMutableArray *)safeArray{
    if (!_safeArray) {
        _safeArray = [NSMutableArray array];
    }
    return _safeArray;
}

-(NSMutableArray *)testArray{
    if (!_testArray) {
        _testArray = [NSMutableArray array];
    }
    return _testArray;
}

-(NSMutableArray *)selectedAssetURLs{
    if(_selectedAssetURLs==nil){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}

- (UIImagePickerController *)picker{
    if(!_picker){
        _picker = [[UIImagePickerController alloc] init];
        _picker.delegate = self;
        _picker.allowsEditing = NO;//设置可编辑
        _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    return _picker;
}

-(TPKeyboardAvoidingTableView *)tableView {
    if(_tableView==nil){
        _tableView=[[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"wuliaoCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"defaineCell"];
        [_tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:kCellIdentifier_H1_ImagesCell];
        [LSUtility setExtraCellLineHidde:self.tableView tabHeader:NO tabFooter:NO];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.00];
    _titleArr = [NSMutableArray arrayWithObjects:@"质检员:",@"专职安全员:",@"试验人员:",@"特种作业人员工种/人数/持证情况:", nil];
    //附件模型
    _curTweet = [[Tweet alloc] init];
    
    [self setData];
    //添加表格
    [self.view addSubview:self.tableView];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_1" object:nil];
    // 查找人员信息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkPeople:) name:@"refreshPeople" object:nil];
}

- (void)setData {
    self.selectedAssetURLs = [LSUtility quertFileImageType:@"RECORD_02_SIDE_01" andId:self.sideId andFilePathArr:self.fileArray];
    [self refresh:nil];
}

// 查找人员信息
- (void)checkPeople:(NSNotification *)notification {
    // 初始化数据源
    [self.iqcArray removeAllObjects];
    [self.safeArray removeAllObjects];
    [self.testArray removeAllObjects];
    
    NSString *constructionUnitID = [notification object];
    if (constructionUnitID) {
        FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
        [db open];
//        NSString *sqlStr;
        for (NSString *peopleType in self.peopleTypeArr) {
            NSString *sqlStr = [NSString stringWithFormat:@"SELECT * FROM PROJECT_USER WHERE UNIT_ID = '%@' AND USER_TYPE = '%@'", constructionUnitID, peopleType];
            
            FMResultSet *result = [db executeQuery:sqlStr];
            while ([result next]) {
                // 用户ID
                NSString *userID = [result stringForColumn:@"USER_ID"];
                // 用户真实姓名
                NSString *realName = [LSUtility getuserIdByUserName:userID][@"REAL_NAME"];
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                [dic setObject:userID forKey:@"USER_ID"];
                [dic setObject:realName forKey:@"REAL_NAME"];
                
                // 质检员
                if ([peopleType isEqualToString:@"CONSTRACT_04"]) {
                    [self.iqcArray addObject:dic];
                    
                // 安全员
                } else if ([peopleType isEqualToString:@"CONSTRACT_05"]) {
                    [self.safeArray addObject:dic];

                // 测试员
                } else if ([peopleType isEqualToString:@"CONSTRACT_06"]) {
                    [self.testArray addObject:dic];
                }
            }
        }
        [db close];
    }
}

- (void)refresh:(id)sender {
    //存在图片
    if(self.selectedAssetURLs!=nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.curTweet.selectedAssetURLs =self.selectedAssetURLs;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:
                 [NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
            });
        });
    }
}

#pragma mark- UITableViewDelagate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0){
        return _titleArr.count;
    }else{
        return 1;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"附件"];
    }else{
        if (indexPath.row==_titleArr.count-1) {
            return 130*BIZ;
        }
        return 44;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    long section=indexPath.section;
    if(section==0){
        if(indexPath.row==_titleArr.count-1){//特种作业人员 多行输入框
            B_wuLiaoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"wuliaoCell" forIndexPath:indexPath];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            //能否编辑
            cell.isEdit = self.isEdit;
            cell.title.text = [_titleArr lastObject];
            cell.text.placeholder = @"请输入人员持证情况：如张拉工/2人持证";
            
            if (self.person.content) {
                cell.text.text = self.person.content;
            }
            cell.textValueChangedBlock = ^(NSString *valueStr){
                self.person.content = valueStr;
            };
            return cell;
            
        }else{
            DefaineCell* cell = [tableView dequeueReusableCellWithIdentifier:@"defaineCell" forIndexPath:indexPath];
            cell.title.text = _titleArr[indexPath.row];
           
            if (indexPath.row == 0) {//质检员
                if(self.person.IQCId){
                    cell.text.text = self.person.IQC;
                } else {
                    cell.text.text=@"请选择";
                }
             }else if (indexPath.row==1){//专职安全员
                if(self.person.safetyId){
                    
                    cell.text.text = self.person.safety;
                }else{
                    cell.text.text=@"请选择";
                }
            }else if (indexPath.row==2){//试验人员
                if (self.person.testId) {
                    cell.text.text = self.person.test;
                    
                }else{
                    cell.text.text=@"请选择";
                }
            }
            return cell;
        }
    }else{
        H1_ImagesCell *cells = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_H1_ImagesCell forIndexPath:indexPath];
        [cells setTitle:@"附件"];
        cells.isEdit=self.isEdit;
        cells.curTweet = _curTweet;
        //添加图片
        cells.addPicturesBlock = ^(){
            [weakSelf showActionForPhoto];
        };
        //删除图片
        __block H1_ImagesCell *cellblock = cells;
        cells.deleteTweetImageBlockUrl = ^(TweetImage *toDelete,NSString *deurl){
            [cellblock.curTweet.tweetImages removeObject:toDelete];
            [weakSelf.selectedAssetURLs removeObject:deurl];
            [weakSelf refresh:nil];
        };
        return cells;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.view endEditing:YES];
    if(self.isEdit && indexPath.section==0){
        if(indexPath.row==0){
            NSNumber *ninit = [NSNumber numberWithInteger:0];
            NSMutableArray *nameArr = [NSMutableArray array];
            if(self.iqcArray.count<1){
                [LSUtility showToastWithMessage:@"无质检员" inView:self.view Andtime:1.5];
                
            } else {
                for (NSDictionary *dic in self.iqcArray) {
                    [nameArr addObject:dic[@"REAL_NAME"]];
                }
                [ActionSheetStringPicker showPickerWithTitle:nil rows:@[nameArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                    //得到选择下标
                    int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
                    NSDictionary *dic = self.iqcArray[iv];
                    self.person.IQC = dic[@"REAL_NAME"];
                    self.person.IQCId = dic[@"USER_ID"];
                    
                    // 修改数据
                    DefaineCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                    cell.text.text = [selectedValue firstObject];
                    
                } cancelBlock:nil origin:self.view];
            }
        }
        else if(indexPath.row==1){
            NSNumber *ninit = [NSNumber numberWithInteger:0];
            NSMutableArray *nameArr = [NSMutableArray array];
            if(self.safeArray.count<1){
                [LSUtility showToastWithMessage:@"无安全员" inView:self.view Andtime:1.5];
                
            } else {
                NSLog(@"%@",self.safeArray);
                for (NSDictionary *dic in self.safeArray) {
                    [nameArr addObject:dic[@"REAL_NAME"]];
                }
                
                [ActionSheetStringPicker showPickerWithTitle:nil rows:@[nameArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                    //得到选择下标
                    int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
                    NSDictionary *dic = self.safeArray[iv];
                    self.person.safety = dic[@"REAL_NAME"];
                    self.person.safetyId = dic[@"USER_ID"];
                    
                    // 修改数据
                    DefaineCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                    cell.text.text = [selectedValue firstObject];
                    
                } cancelBlock:nil origin:self.view];
            }
        }
        else if(indexPath.row==2){
            NSNumber *ninit = [NSNumber numberWithInteger:0];
            NSMutableArray *nameArr = [NSMutableArray array];
            if(self.testArray.count<1){
                [LSUtility showToastWithMessage:@"无测试员" inView:self.view Andtime:1.5];
            } else {
                for (NSDictionary *dic in self.testArray) {
                    [nameArr addObject:dic[@"REAL_NAME"]];
                }
                [ActionSheetStringPicker showPickerWithTitle:nil rows:@[nameArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                    //得到选择下标
                    int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
                    NSDictionary *dic = self.testArray[iv];
                    self.person.test = dic[@"REAL_NAME"];
                    self.person.testId = dic[@"USER_ID"];
                    // 修改数据
                    DefaineCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                    cell.text.text = [selectedValue firstObject];
                    
                } cancelBlock:nil origin:self.view];
            }            
        }
    }
}

#pragma mark UIActionSheet M
- (void)showActionForPhoto {
    //    @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (_curTweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
        [self presentViewController:self.picker animated:YES completion:nil];//进入照相界面
    }else if (buttonIndex == 1){
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages=[[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock=^(NSMutableArray *array){
            for (NSString *path in array) {
                //添加图片路径到已选数组
                [self.selectedAssetURLs addObject:path];
            }
        };
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        //添加选择附件
        [weakSelf.curTweet addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs addObject:path];
        //刷新指定行
        [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end

